<template>
  <div class="table-management-container">
    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item>
          <el-select v-model="filterForm.store" placeholder="请选择门店" clearable style="width: 180px">
            <el-option
                v-for="store in storeOptions"
                :key="store.id"
                :label="store.name"
                :value="store.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select v-model="filterForm.tableType" placeholder="请选择桌位" clearable style="width: 180px">
            <el-option
                v-for="type in tableTypeOptions"
                :key="type.label"
                :label="type.label"
                :value="type.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select v-model="filterForm.status" placeholder="请选择使用状态" clearable style="width: 180px">
            <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAddTable">新建台桌</el-button>
      <el-button @click="handleTableTypeManagement">桌型管理</el-button>
      <el-button @click="handleReservationSetting">预订设置</el-button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="storeVO.name" label="所属门店" width="210" />
        <el-table-column prop="tableNumber" label="桌号" width="100" />
        <el-table-column prop="seats" label="桌位" width="120" />
        <el-table-column prop="tableTypes.name" label="桌型" width="150" />
        <el-table-column label="使用状态" width="90">
          <template #default="{row}">
            <el-tag :type="row.usageStatus === 1 ? 'danger' : 'success'">
              {{ usageStatusMap[row.usageStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabledStatus" label="启用状态" width="110">
          <template #default="{row}">
            <el-switch
                v-model="row.enabledStatus"
                :active-value="1"
                :inactive-value="0"
                disabled= false
                @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="285">
          <template #default="{row}">
<!--            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>-->
            <el-button size="small" type="danger" @click="handleRemove(row)">删除</el-button>
            <el-button size="small" type="info" @click="handleViewQrCode(row)">查看二维码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="二维码" v-model="dialogVisible" width="30%">
        <img :src="qrCodeUrl" alt="二维码" style="width: 100%; height: auto;">
      </el-dialog>

      <!-- 批量操作和分页 -->
      <div class="bottom-container">
        <el-button
            type="danger"
            :disabled="selectedTables.length === 0"
            @click="handleRemove"
        >
          批量删除
        </el-button>

        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :small="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: 'TableManagement',
  data() {
    return {
      // 筛选表单
      filterForm: {
        store: '',
        tableType: '',
        status: ''
      },

      // 二维码相关
      qrCodeUrl: '',
      dialogVisible: false,

      // 下拉选项
      storeOptions: [],
      tableTypeOptions: [
        { value: '1', label: '大厅' },
        { value: '2', label: '包间' },
      ],
      statusOptions: [
        { value: '1', label: '使用' },
        { value: '2', label: '空闲' }
      ],

      // 使用状态映射
      usageStatusMap: {
        1: '使用',
        0: '空闲'
      },


      // 表格数据
      tableData: [],
      selectedTables: [],
      queryParams: {
        store: '',
        tableType: '',
        status: ''
      },

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.fetchTableData();
    this.getAllStores();
  },
  methods: {
    // 获取表格数据
    fetchTableData() {
      axios.post(`table/allTable/${this.currentPage}/${this.pageSize}`,this.filterForm).then(res => {
        this.tableData = res.data.obj.data;
        console.log(res.data.obj.data);
        this.total = res.data.obj.total;
      });
    },

    // 查看二维码
    handleViewQrCode(row) {
      if (row.qrCode) {
        this.qrCodeUrl = row.qrCode;
        console.log(this.qrCodeUrl);
        this.dialogVisible = true;
      } else {
        ElMessage.warning('该桌位没有二维码');
      }
    },

    // 获取所有店名
    getAllStores() {
      axios.get(`store/getStoreName`).then(res => {
        this.storeOptions = res.data
      });
    },

    // 查询
    handleQuery() {
      //this.currentPage = 1;
      console.log('查询条件:', this.filterForm);
      this.fetchTableData()
    },

    // 选择变化
    handleSelectionChange(val) {
      this.selectedTables = val.map(row => row.id);
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData({
        store: this.filterForm.store,
        tableType: this.filterForm.tableType,
        status: this.filterForm.status
      });
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData({
        store: this.filterForm.store,
        tableType: this.filterForm.tableType,
        status: this.filterForm.status
      });
    },

    // 查看
    handleView(row) {
      this.$message.info(`查看桌位: ${row.tableName}`);
      // 实际项目中可以打开详情对话框或跳转到详情页
    },

    // 编辑
    handleEdit(row) {
      this.$router.push('/create');
    },

    // 删除请求
    handleRemoveRequest() {
      axios.post(`table/deleteTable/`, this.selectedTables).then(res => {
        ElMessage.success(res.data.msg)
        this.fetchTableData();
      }).catch(err=> {
        ElMessage.error('请求失败')
      })
    },
    // 删除
    handleRemove(row) {
      if (row.id !== undefined) {
        this.selectedTables.push(row.id);
      }
      ElMessageBox.confirm('确定要删除选中的桌位吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleRemoveRequest();
        this.selectedTables = [];
      }).catch(() => {
        this.selectedTables = [];
        this.$message.info('已取消删除');
      });
    },

    // 状态改变
    handleStatusChange(row) {
      // 这里应该是调用API更新状态
      this.$message.success(`桌位 ${row.tableName} 状态已更新`);
    },

    // 添加桌位
    handleAddTable() {
      // 跳转到添加桌位页面
      this.$router.push('/create');
    },

    // 桌型管理
    handleTableTypeManagement() {
      this.$message.info('跳转到桌型管理页面');
      // 跳转到相应页面
      this.$router.push('/type');
    },

    // 预订设置
    handleReservationSetting() {
      this.$message.info('跳转到预订设置页面');
      // 跳转到相应页面
      this.$router.push('/booking');
    },

    // 对话框确认
    handleConfirm() {
      if (this.isEdit) {
        // 调用API更新
        this.$message.success('桌位更新成功');
      } else {
        // 调用API添加
        this.$message.success('桌位添加成功');
      }
      this.dialogVisible = false;
      this.fetchTableData({
        store: this.filterForm.store,
        tableType: this.filterForm.tableType,
        status: this.filterForm.status
      });
    }
  }
}
</script>

<style scoped>
.table-management-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.operation-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.bottom-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.el-pagination {
  margin-top: 15px;
}
</style>
